import { app, BrowserWindow, Menu, ipcMain } from 'electron'
import { fileURLToPath } from 'url'
import { dirname, join, resolve } from 'path'
import { existsSync } from 'fs'
import store from './store.js'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

// 保持对窗口对象的全局引用，否则窗口会被自动关闭
let mainWindow

function createWindow() {
  // 创建浏览器窗口 - 沉浸式 macOS 风格
  const isMac = process.platform === 'darwin'
  
  const windowOptions = {
    width: 1200,
    height: 800,
    minWidth: 800,
    minHeight: 600,
    frame: false, // 无边框窗口
    transparent: false,
    backgroundColor: '#f7f7f2',
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: resolve(__dirname, 'preload.js')
    },
    icon: join(__dirname, '../build/icon.png'),
    shadow: true // 窗口阴影
  }
  
  // macOS 特定选项
  if (isMac) {
    windowOptions.titleBarStyle = 'hidden' // macOS 隐藏标题栏
    windowOptions.titleBarOverlay = {
      color: '#667eea',
      symbolColor: '#ffffff',
      height: 40
    }
    windowOptions.vibrancy = 'ultra-dark' // macOS 毛玻璃效果
    windowOptions.visualEffectState = 'active' // macOS 视觉效果状态
    windowOptions.roundedCorners = true // 圆角窗口
  }
  
  // 调试：检查 preload 路径
  const preloadPath = resolve(__dirname, 'preload.js')
  console.log('[main] Preload path:', preloadPath)
  console.log('[main] Preload exists:', existsSync(preloadPath))
  
  mainWindow = new BrowserWindow(windowOptions)

  // 监听 preload 错误
  mainWindow.webContents.on('preload-error', (event, preloadPath, error) => {
    console.error('[main] Preload error:', preloadPath, error)
  })
  
  // 监听 DOM 就绪
  mainWindow.webContents.on('dom-ready', () => {
    console.log('[main] DOM ready')
  })
  
  // 监听渲染进程就绪
  mainWindow.webContents.on('did-finish-load', () => {
    console.log('[main] Page finished loading')
    // 延迟检查，确保 preload 已执行
    setTimeout(() => {
      // 检查 window.electronAPI 是否可用
      mainWindow.webContents.executeJavaScript(`
        console.log('[renderer] window.electronAPI:', typeof window.electronAPI !== 'undefined' ? 'exists' : 'undefined')
        console.log('[renderer] window.electronAPI.window:', typeof window.electronAPI?.window !== 'undefined' ? 'exists' : 'undefined')
        if (window.electronAPI?.window) {
          console.log('[renderer] window.electronAPI.window methods:', Object.keys(window.electronAPI.window))
        }
      `).catch(err => console.error('[main] Execute script error:', err))
    }, 500)
  })

  // 加载应用
  const isDev = process.env.NODE_ENV === 'development' || !app.isPackaged
  
  if (isDev) {
    // 开发环境：加载 Vite 开发服务器
    mainWindow.loadURL('http://localhost:5173')
    // 打开开发者工具
    mainWindow.webContents.openDevTools()
  } else {
    // 生产环境：加载打包后的文件
    // 打包后文件在 resources/app.asar 或 resources/app/dist 目录下
    let distPath
    if (app.isPackaged) {
      // 打包后的路径：resources/app.asar/dist/index.html
      const appPath = app.getAppPath()
      console.log('[main] App path:', appPath)
      console.log('[main] Resources path:', process.resourcesPath)
      
      // 尝试多个可能的路径
      const possiblePaths = [
        join(appPath, 'dist/index.html'),
        join(process.resourcesPath, 'app.asar/dist/index.html'),
        join(process.resourcesPath, 'app/dist/index.html'),
        join(appPath, 'index.html')
      ]
      
      distPath = possiblePaths.find(path => existsSync(path))
      
      if (!distPath) {
        console.error('[main] Could not find index.html in any of these paths:')
        possiblePaths.forEach(p => console.error('  -', p, existsSync(p) ? 'EXISTS' : 'NOT FOUND'))
        distPath = possiblePaths[0] // 使用第一个路径作为默认值
      }
    } else {
      distPath = join(__dirname, '../dist/index.html')
    }
    
    console.log('[main] Loading dist path:', distPath)
    console.log('[main] Dist path exists:', existsSync(distPath))
    
    // 使用 loadFile 加载本地文件
    mainWindow.loadFile(distPath).catch(err => {
      console.error('[main] Failed to load file:', err)
      // 如果 loadFile 失败，尝试使用 loadURL
      const fileUrl = `file://${distPath.replace(/\\/g, '/')}`
      console.log('[main] Trying loadURL:', fileUrl)
      mainWindow.loadURL(fileUrl).catch(urlErr => {
        console.error('[main] Failed to load URL:', urlErr)
        // 打开开发者工具以便调试
        mainWindow.webContents.openDevTools()
      })
    })
  }

  // 当窗口被关闭时
  mainWindow.on('closed', () => {
    mainWindow = null
  })
  
  // 创建中文菜单
  createMenu()
  
  // 设置 IPC 处理
  setupIPC()
}

// 创建中文菜单
function createMenu() {
  const template = [
    {
      label: '文件',
      submenu: [
        {
          label: '退出',
          accelerator: process.platform === 'darwin' ? 'Cmd+Q' : 'Ctrl+Q',
          click: () => {
            app.quit()
          }
        }
      ]
    },
    {
      label: '编辑',
      submenu: [
        { label: '撤销', accelerator: 'CmdOrCtrl+Z', role: 'undo' },
        { label: '重做', accelerator: 'Shift+CmdOrCtrl+Z', role: 'redo' },
        { type: 'separator' },
        { label: '剪切', accelerator: 'CmdOrCtrl+X', role: 'cut' },
        { label: '复制', accelerator: 'CmdOrCtrl+C', role: 'copy' },
        { label: '粘贴', accelerator: 'CmdOrCtrl+V', role: 'paste' },
        { label: '全选', accelerator: 'CmdOrCtrl+A', role: 'selectAll' }
      ]
    },
    {
      label: '查看',
      submenu: [
        { label: '重新加载', accelerator: 'CmdOrCtrl+R', role: 'reload' },
        { label: '强制重新加载', accelerator: 'CmdOrCtrl+Shift+R', role: 'forceReload' },
        { label: '切换开发者工具', accelerator: process.platform === 'darwin' ? 'Alt+Cmd+I' : 'Ctrl+Shift+I', role: 'toggleDevTools' },
        { type: 'separator' },
        { label: '实际大小', accelerator: 'CmdOrCtrl+0', role: 'resetZoom' },
        { label: '放大', accelerator: 'CmdOrCtrl+Plus', role: 'zoomIn' },
        { label: '缩小', accelerator: 'CmdOrCtrl+-', role: 'zoomOut' },
        { type: 'separator' },
        { label: '切换全屏', accelerator: process.platform === 'darwin' ? 'Ctrl+Cmd+F' : 'F11', role: 'togglefullscreen' }
      ]
    },
    {
      label: '窗口',
      submenu: [
        { label: '最小化', accelerator: 'CmdOrCtrl+M', role: 'minimize' },
        { label: '关闭', accelerator: 'CmdOrCtrl+W', role: 'close' }
      ]
    },
    {
      label: '帮助',
      submenu: [
        {
          label: '关于',
          click: () => {
            // 可以显示关于对话框
          }
        }
      ]
    }
  ]

  // macOS 特殊处理
  if (process.platform === 'darwin') {
    template.unshift({
      label: app.getName(),
      submenu: [
        { label: '关于 ' + app.getName(), role: 'about' },
        { type: 'separator' },
        { label: '服务', role: 'services', submenu: [] },
        { type: 'separator' },
        { label: '隐藏 ' + app.getName(), accelerator: 'Command+H', role: 'hide' },
        { label: '隐藏其他', accelerator: 'Command+Shift+H', role: 'hideOthers' },
        { label: '显示全部', role: 'unhide' },
        { type: 'separator' },
        { label: '退出', accelerator: 'Command+Q', click: () => app.quit() }
      ]
    })
  }

  const menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu)
}

// 设置 IPC 处理
function setupIPC() {
  // 窗口控制
  ipcMain.handle('window:minimize', () => {
    if (mainWindow && !mainWindow.isDestroyed()) {
      mainWindow.minimize()
      return true
    }
    return false
  })
  
  ipcMain.handle('window:maximize', () => {
    if (mainWindow && !mainWindow.isDestroyed()) {
      if (mainWindow.isMaximized()) {
        mainWindow.unmaximize()
      } else {
        mainWindow.maximize()
      }
      return true
    }
    return false
  })
  
  ipcMain.handle('window:close', () => {
    if (mainWindow && !mainWindow.isDestroyed()) {
      mainWindow.close()
      return true
    }
    return false
  })
  
  ipcMain.handle('window:isMaximized', () => {
    if (mainWindow && !mainWindow.isDestroyed()) {
      return mainWindow.isMaximized()
    }
    return false
  })
  
  // 存储：获取
  ipcMain.handle('storage:get', async (event, keys) => {
    const result = {}
    const keyArray = Array.isArray(keys) ? keys : Object.keys(keys || {})
    
    for (const key of keyArray) {
      const value = store.get(key)
      if (value !== undefined) {
        result[key] = value
      }
    }
    
    return result
  })
  
  // 存储：设置
  ipcMain.handle('storage:set', async (event, items) => {
    const changes = {}
    
    for (const [key, value] of Object.entries(items)) {
      const oldValue = store.get(key)
      store.set(key, value)
      changes[key] = { oldValue, newValue: value }
    }
    
    // 通知渲染进程存储变化
    if (mainWindow && !mainWindow.isDestroyed()) {
      mainWindow.webContents.send('storage:changed', changes, 'local')
    }
    
    return true
  })
  
  // 存储：删除
  ipcMain.handle('storage:remove', async (event, keys) => {
    const changes = {}
    const keyArray = Array.isArray(keys) ? keys : [keys]
    
    for (const key of keyArray) {
      const oldValue = store.get(key)
      if (oldValue !== undefined) {
        store.delete(key)
        changes[key] = { oldValue, newValue: null }
      }
    }
    
    // 通知渲染进程存储变化
    if (mainWindow && !mainWindow.isDestroyed()) {
      mainWindow.webContents.send('storage:changed', changes, 'local')
    }
    
    return true
  })
}

// Electron 初始化完成后创建窗口
app.whenReady().then(() => {
  createWindow()

  app.on('activate', () => {
    // 在 macOS 上，当点击 dock 图标并且没有其他窗口打开时，
    // 通常在应用程序中重新创建一个窗口
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})

// 当所有窗口都被关闭时退出应用
app.on('window-all-closed', () => {
  // 在 macOS 上，除非用户用 Cmd + Q 确定地退出，
  // 否则绝大部分应用程序及其菜单栏会保持激活
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
